package jobhunter.repository;

import java.util.List;

import jobhunter.model.Company;
import jobhunter.model.Process;
import jobhunter.security.SecurityContext;
import jobhunter.tool.JpaResultHelper;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@SuppressWarnings("unchecked")
public class ProcessRepository extends GenericRepositoryJpa<Process>
{
	public ProcessRepository() {
		setEntityClass(Process.class);
	}
	
	public List<Process> findByCompany(Company company)
	{
		return (List<Process>)em.createQuery("SELECT p FROM Process p WHERE p.company=:company AND p.user =:user ORDER BY p.id ASC")
				.setParameter("company", company).setParameter("user", SecurityContext.getUser()).getResultList();
	}
	public Process findLastOfCompany(Company company)
	{
		return (Process) JpaResultHelper.getSingleResultOrNull(em.createQuery("SELECT p FROM Process p WHERE p.company=:company AND p.user =:user ORDER BY p.id ASC")
				.setParameter("company", company).setParameter("user", SecurityContext.getUser()));
	}

	public Process findByIdWithActions(Long id)
	{
		return (Process) JpaResultHelper.getSingleResultOrNull(em.createQuery("SELECT p FROM Process p LEFT JOIN FETCH p.actions Where p.id = :id AND p.user =:user ORDER BY p.id")
				.setParameter("id", id).setParameter("user", SecurityContext.getUser()));
	}
	

	
	@Override
	public Process merge(Process t) {
		if(t.getUser()==SecurityContext.getUser())
			return em.merge(t);
		else
			return null;
	}
	@Override
	public void remove(Process t) 
	{
		if(t.getUser()==SecurityContext.getUser())
			em.remove(t);		
	}

}
